<?php

namespace payment;

/**
 * 完美支付 SDK
 */
class Wanmei{

/**
地址：http://129.211.49.184/index/panel/home.do
账号：baotetv
密码：baotetv
*/
	public function pay_url($args){
		$s_key = $this->private_key();
		// account_id=22&amount=1.01&callback_url=http://www.baidu.com&content_type=json&error_url=http://www.baidu.com&out_trade_no=1902019062612124401&robin=2&success_url=http://www.baidu.com&thoroughfare=service_auto&type=3
		$res = openssl_pkey_get_private($s_key);
		// echo $res."<br/>";
		
		//account_id=22&amount=1.01&callback_url=http://www.baidu.com&content_type=json&error_url=http://www.baidu.com&out_trade_no=1902019062612124401&robin=2&success_url=ht://www.baidu.com&thoroughfare=server_auto&type=3
		//当前界面是进行网关参数获取以及发起POST请求
		//下面参数均为商户自定义，可自行修改
		//请求获取的网页类型，json 返回json数据，text直接跳转html界面支付，如没有特殊需要，建议默认text即可
		$content_type = isset($args['content_type']) ? $args['content_type'] : 'json';
		//商户ID->到平台首页自行复制粘贴
		$account_id   = isset($args['account_id']) ? $args['account_id'] : '24';
		$thoroughfare = isset($args['thoroughfare']) ? $args['thoroughfare'] : 'service_auto';
		$type         = isset($args['type']) ? $args['type'] : '3';
		//订单号码->这个是四方网站发起订单时带的订单信息，一般为用户名，交易号，等字段信息
		$out_trade_no = isset($args['out_trade_no']) ? $args['out_trade_no'] : '1902019062612124401';
		//支付金额
		$amount       = isset($args['amount']) ? $args['amount'] : '1.00';
		//轮训状态，是否开启轮训，状态 1 为关闭   2为开启
		$robin        = 2;
		//异步通知接口url->用作于接收成功支付后回调请求
		$callback_url = isset($args['callback_url']) ? $args['callback_url'] : '';
		//支付成功后自动跳转url
		$success_url  = isset($args['success_url']) ? $args['success_url'] : '';
		//支付失败或者超时后跳转url
		$error_url    = isset($args['error_url']) ? $args['error_url'] : '';

		//支付类型->类型参数是服务版使用，公开版无需传参也可以
		$post_data['account_id']   = $account_id;
		$post_data['content_type'] = $content_type;
		$post_data['thoroughfare'] = $thoroughfare;
		$post_data['out_trade_no'] = $out_trade_no;
		$post_data['robin']        = $robin;
		$post_data['callback_url'] = $callback_url;
		$post_data['success_url']  = $success_url;
		$post_data['error_url']    = $error_url;
		$post_data['amount']       = $amount;
		$post_data['type']         = '3';
		$mystr = $this->asc_sort($post_data);
		//签名
		$sign = $this->rsaSign($mystr, $s_key);
		$post_data['sign'] = urlencode($sign);
		$ret  = json_decode($this->request_post('http://129.211.49.184/gateway/index/checkpoint.do', $post_data),true);
		log_to($ret, "paySDKpay-Wanmei");
		if($ret['code'] == 200){
			$rs['out_trade_no'] = $ret['data']['order_id'];
			$rs['alipay'] = $ret['data']['alipay'];
			$rs['wechat'] = $ret['data']['wechat'];
			return $rs;	
		} 
		return false;
	}

	public function response(){
		log_to($_POST, "paySDKCallback-Wanmei");
		$s_key = $this->private_key();
		//$data =urldecode($_POST['sign']);
		$data = 'hy%2B1o9iHQzx1vFev1aiv3%2FOAMThqjrJOW9rtbvhAC12kGCDJgS4ibUHKjrtzncvIT0FTVkDYSRRyU6uFT5S7MNyICnGRMAOxwK00EMXK9QqaPVk96AIvkl5I6Twf%2FnG9jM2ah7ZE0yPym4TOfUvR4E9OuySFmKeziaateDCiAPmX8Yg0bt2B5hS10tQ7tyjRPOtlWI2YKRi5LEOnFFzY6KaPSjm8Sfu%2FQrzdn9uTD76g56BnfKWHv%2BfEDM%2BpSxEiiWi9WppbYIrr%2F8VGN%2FJwKXNGaMgsVfRfRMh9Uho69QKtqb6HLvS7XaCv72q79%2FQTP5MRAgPZWT3oNPsP6b5eHX8vx9FwZoe35B6L3sQdsMripJW0QLsQD7FKLxtRmEQu0oPzfYdKY8TIIsal%2B6hCP79D7nDFHyGyA9LpG3lVw81oD0g%2BcCQMoG4pgbPTzIzXwZ6NL9f3jvDlc21jNkDdDBaf4Uk3muefGUsGYKiwfEx6da0%2FVrDunKFy2rKxlhDw1bP8F4M9SsB8X%2FSOtaAbt2ZP2ybMzXpv7f6aoyGdhuocCZkmxpoWNqeQzNdoSOY4ZDZn2cl8a8jV2FyXCtZLzNS5JvexCPVrcM8tpdoVyrVbI%2BtG93KMD4%2BchJxd%2F0%2FN3CSAKV6xdZx8jAqGbn0EfVOsawr9%2B7uTQzWP8g%2FROJA%3D';
		openssl_private_decrypt(base64_decode($data), $decrypted, $s_key);//私钥解密
		
		$rsa_arr = [
			'status'        => 'success',
			'amount'        => @$_REQUEST['amount'],
			'amount_true'   => @$_REQUEST['amount_true'],
			'out_trade_no'  => @$_REQUEST['out_trade_no'],
			'trade_no'      => @$_REQUEST['trade_no'],
			'fees'          => @$_REQUEST['fees'],
			'callback_time' => @$_REQUEST['callback_time'],
			'type'          => @$_REQUEST['type'],
		];
		// file_put_contents("callback_wanmei2.txt", $this->asc_sort($rsa_arr).$decrypted);
		log_to($rsa_arr, "paySDKCallback-Wanmei");
		$rs = [];
		$rs['status']     = ($rsa_arr['status'] == 'success') ? 1 : 2;
		$rs['order_sn']   = $rsa_arr['out_trade_no'];
		$rs['money_real'] = $rsa_arr['amount_true'];
		return $rs;
		// if($this->asc_sort($rsa_arr) == $decrypted){
		// 	$rs['status']     = ($rsa_arr['status'] == 'success') ? 1 : 2;
		// 	$rs['order_sn']   = $rsa_arr['trade_no'];
		// 	$rs['money_real'] = $rsa_arr['amount_true'];
		// 	return $rs;	
		// }else{
		// 	return false;
		// }
	}



	private function private_key(){
		return <<<EOF
-----BEGIN PRIVATE KEY-----
MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQC9/0Xop8/KGCzT
gQYm03CBtdmXVrqjKqxx70vM98TA9U57DDHmOCtYPgarkbPe01ziPa27eDciyzgN
Uv2sC2sz7zoxSld1oMDXwEvTiGARV9315+96ZNxR5K9Ym8Hv3Q+uK3ZzNq04HMwu
FIXkt3fKDSS/4+VdSlqXp9fxIOAl/N9t9/fIiazEIILJP43S7WrIYURpIZW3MsWn
vawmAL9cZgmuBGBqg56ZrX6rL9y1rwLiAcOJSFh/GIRfAxvdw0co5RBIdmOO0Gpo
4JEsvMx7JXn9ISUpFqKrF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C835J/6esH+K5m8RQtaRp0+yIjwjAoIBAB1FOY7WVyt6C2N/yrvA
9o4go6M/Vlnojm9J9so0dJ4zArcf/txQgYbpIzExXIv/DDOuo1JTS4OjFztrLmks
1bl7g5iyw9Tl1BWYioH2SbJ4cRC6goC+FH0i0MBzPqDH5jE3mK/vC1JWZXASh2FZ
u/fD5OrycJLRFGuzGwabz2OlFXhvzZ7/uXYZac2r/S8c06b+8YlROUhdM9zkKTXn
xL7WusCM6NIolpNP2gu6R6l5+ZN+AINGr7uAW1k1T2PmUetFtfvxRF2oJSMRJXiY
+cmX78k+fi23+afhakt42UM0p1tDecUyJz1J+Ku8H5I+tNW1Cxpol0sIza9Qxz3x
26kCggEAX4ZPNEV6A5bDBAWTbtP2GgFWWFLA8eFoUiBZpML0Hr32v46ojGio+/IT
YkasSXEQMa/aMkmanPZdKguyDZQ2kdTgblQ3FGYxHtozqBq6LJO8Zt4dgDMnSVoT
xeuI1cPa6us7ip9EkcnDYSEIRB0KRedd6fCO5JWXt5lGkHnLoxYG9e6RgtaaDDzL
V9TZMdF8p3d6hVgEJd/DdBXPj3ssOSjQ0UkgAwd4PtT2JdT048rsP1txPxcbfPKm
RnL6gXmQ+6h3yIJDxyd8ZZ4TluKS7U0+fRZLgy7I4PdkJDGkcOMnyd0FV3jyqF3A
fhVs/cd8yKnQv0zs9ld0Tr6K94u33Q==
-----END PRIVATE KEY-----
EOF;
	}
	
	private function request_post($url = '', $post_data = array()){
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $o = "";
        foreach ( $post_data as $k => $v ) 
        { 
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }
	private function  asc_sort($params = array()){
        if (!empty($params)) {
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    $str .= $k . '=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                return $strs;
            }
        }
        return false;
    }
	/**
	 * RSA签名
	 * @param $data 待签名数据
	 * @param $private_key_path 商户私钥文件路径
	 * return 签名结果
	 */
	private function rsaSign($data, $priKey){
	    $res = openssl_get_privatekey($priKey);
	    openssl_sign($data, $sign, $res);
	    openssl_free_key($res);
	    //base64编码
	    $sign = base64_encode($sign);
	    return $sign;
	}
	/**RSA验签
	 * $data待签名数据
	 * $sign需要验签的签名
	 * 验签用支付宝公钥
	 * return 验签是否通过 bool值
	 */
	private function verify($data, $sign,$pubKey){
	    //转换为openssl格式密钥
	    $res = openssl_get_publickey($pubKey);
	    //调用openssl内置方法验签，返回bool值
	    $result = (bool)openssl_verify($data, base64_decode($sign), $res);
	    //释放资源
	    openssl_free_key($res);
	    //返回资源是否成功
	    return $result;
	}
    

}